﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BankApplication.BusinessLogic;
using BusinessLogic.BusinessEntity.Entities;

namespace BankApplication.UI
{
	public partial class CurrencyForm : Form
	{
		public CurrencyForm()
		{
			InitializeComponent();
		}

		private const int MAX_CODE_LENGTH = 3;
		private const int MAX_NAME_LENGTH = 50;

		private void ValidateForm()
		{
			if (CurrencyCodeTextBox.Text.Equals(string.Empty))
			{
				throw new ValidationException("Currency code cannot be empty!");
			}

			if (CurrencyCodeTextBox.Text.Length > MAX_CODE_LENGTH)
			{
				throw new ValidationException(String.Format("Currency code cannot be more than {0} characters long!", MAX_CODE_LENGTH)); 
			}

			if (!ValidationHelper.IsNumberical(CurrencyCodeTextBox.Text))
			{
				throw new ValidationException("Currency code must comprise only the digits from 0 to 9!");
			}


			if (CurrencyNameTextBox.Text.Equals(string.Empty))
			{
				throw new ValidationException("Currency name cannot be empty!");
			}

			if (CurrencyNameTextBox.Text.Length > MAX_NAME_LENGTH)
			{
				throw new ValidationException(String.Format("Currency name cannot be more than {0} characters long!", MAX_NAME_LENGTH));
			}
		}

		private void CloseButton_Click(object sender, EventArgs e)
		{
			Close();
		}

		private void AddCurrencyButton_Click(object sender, EventArgs e)
		{
			try
			{
				ValidateForm();

				Currency currency = new Currency();
				currency.Code = CurrencyCodeTextBox.Text;
				currency.Name = CurrencyNameTextBox.Text;

				new ServerInteractionExceptionCatcher().Execute(() =>
				{
					CurrenciesManager.CreateCurrency(currency, SessionManager.Instance.SessionTicket);

					Close();
				});
			}
			catch (ValidationException exception)
			{
				MessageBox.Show(exception.Message, "Form validation failed!", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}
	}
}
